#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Job {
    char id;
    int arrival_time;
    int burst_time;
    int remaining_time;

    bool operator==(const Job& other) const {
        return id == other.id;
    }
};

bool compareArrivalTime(const Job& a, const Job& b) {
    return a.arrival_time < b.arrival_time;
}

void shortestJobFirst(vector<Job>& jobs) {
    sort(jobs.begin(), jobs.end(), compareArrivalTime);

    int current_time = 0;
    int total_turnaround_time = 0;

    cout << "作业到达顺序：";
    for (const auto& job : jobs) {
        cout << job.id << " -> ";
    }
    cout << endl;

    cout << "作业ID   到达时间   预计运行时间" << endl;
    for (const auto& job : jobs) {
        cout << job.id << "        " << job.arrival_time << "         " << job.burst_time << endl;
    }

    for (int i = 0; i < jobs.size(); ++i) {
        Job current_job = jobs[i];
        int turnaround_time = current_time - current_job.arrival_time;
        total_turnaround_time += turnaround_time;
        cout << "时刻 " << current_time << ": 开始运行作业 " << current_job.id << endl;
        current_time += current_job.burst_time;
        cout << "时刻 " << current_time << ": 作业 " << current_job.id << " 完成" << endl;
    }

    cout << "平均周转时间为: " << (double)total_turnaround_time / jobs.size() << endl;
}

void shortestRemainingTimeNext(vector<Job>& jobs) {
    sort(jobs.begin(), jobs.end(), compareArrivalTime);

    int current_time = 0;
    int total_turnaround_time = 0;

    cout << "作业到达顺序：";
    for (const auto& job : jobs) {
        cout << job.id << " -> ";
    }
    cout << endl;

    cout << "作业ID   到达时间   预计运行时间" << endl;
    for (const auto& job : jobs) {
        cout << job.id << "        " << job.arrival_time << "         " << job.burst_time << endl;
    }

    while (!jobs.empty()) {
        auto shortest_job = min_element(jobs.begin(), jobs.end(), 
            [](const Job& a, const Job& b) { return a.remaining_time < b.remaining_time; });

        cout << "时刻 " << current_time << ": 开始运行作业 " << shortest_job->id << endl;
        current_time++;
        shortest_job->remaining_time--;

        if (shortest_job->remaining_time == 0) {
            int turnaround_time = current_time - shortest_job->arrival_time;
            total_turnaround_time += turnaround_time;
            cout << "时刻 " << current_time << ": 作业 " << shortest_job->id << " 完成" << endl;
            jobs.erase(remove(jobs.begin(), jobs.end(), *shortest_job), jobs.end());
        }
    }

    cout << "平均周转时间为: " << (double)total_turnaround_time / jobs.size() << endl;
}

int main() {
    vector<Job> jobs = {
        {'A', 0, 4, 4},
        {'B', 1, 3, 3},
        {'C', 2, 2, 2}
    };

    cout << "最短作业优先 (SJF) 调度算法：" << endl;
    shortestJobFirst(jobs);

    cout << endl << "最短剩余时间优先 (SRTN) 调度算法：" << endl;
    shortestRemainingTimeNext(jobs);

    return 0;
}
